﻿using MathTutorPro.DAL;
using MathTutorPro.Data.Entities;
using Microsoft.EntityFrameworkCore;

namespace MathTutorPro.Data.DAL
{
    public class GroupChatDal
    {
        private readonly AppDbContext _context;

        private readonly GroupChatMemberDal _memberDal;


        public GroupChatDal(AppDbContext context,
        GroupChatMemberDal memberDal)
        {
            _context = context;
            _memberDal = memberDal;
        }

        public async Task<ChatGroup> CreateGroupAsync(ChatGroup group)
        {
            await _context.ChatGroup.AddAsync(group);
            await _context.SaveChangesAsync();
            return group;
        }
        //获取群聊列表（根据用户ID）
        public async Task<IEnumerable<ChatGroup>> GetGroupsByUserIdAsync(string userId)
        {
            return await _context.ChatGroup
                .Include(g => g.Members)
                .Include(g => g.CreateUser)
                .Include(g => g.Messages.OrderByDescending(m => m.SentTime).Take(1))
                .Where(g => g.Members.Any(m => m.UserId == userId && !m.IsDelete) && !g.IsDelete)
                .AsNoTracking()
                .ToListAsync();
        }
        public async Task<ChatGroup?> GetGroupByIdAsync(int groupId)
        {
            return await _context.ChatGroup
                .AsNoTracking()
                .FirstOrDefaultAsync(g => g.Id == groupId && !g.IsDelete);
        }
        public async Task<ChatGroup?> GetGroupDetailAsync(int groupId)
        {
            var group = await _context.ChatGroup
                .Include(g => g.Members)
                    .ThenInclude(m => m.User) // 加载成员的用户信息
                .Include(g => g.Messages)    // 如果需要最新消息
                .FirstOrDefaultAsync(g => g.Id == groupId && !g.IsDelete);

            return group;
        }


        public async Task<IEnumerable<ChatGroup>> GetGroupsByClassIdAsync(int classId)
        {
            return await _context.ChatGroup
                .Where(g => g.ClassId == classId && !g.IsDelete)
                .ToListAsync();
        }






    }
}
